import pandas as pd
import csv
import os
from IPython import embed
from git import Repo
from mailing import send_mail_cse_smtp
from collections import defaultdict
from sys import argv
import traceback
import logging


def gen_link_mail(sid):
    sid = str(sid)
    if len(sid) != 10:
        raise RuntimeError("Wrong SID {}".format(sid))
    return sid + "@link.cuhk.edu.hk"


n_students = 5  # how many students in one team
phase = "Init code mark"
subject = "CSCI3100 Project Initial Code Marking"
text = """Dear Group {},

Below is the mark of your CSCI3100 project initial code.

Project Name: {}
Mark: {}

We are pleased to see that most groups' code repositories are quite comprehensive. Looking forward to seeing your awesome project on the demo day!

You might receive this email a little bit later than your teammates. Don't worry because this was only caused by some technical problems. 

Regards,
CSCI3100 TA Group"""


if __name__ == "__main__":
    group_info = pd.read_csv("./final-group.csv")
    mark_info = pd.read_excel(
        "./marks/initial code/CSCI3100-2021 Project Initial Code Marking.xlsx"
    )

    gid_projname = dict(zip(group_info["Group ID"], group_info["Project Name"]))
    gid_url = dict(zip(group_info["Group ID"], group_info["URL"]))
    gid_mark = dict(zip(mark_info["Group ID"], mark_info["Mark"]))

    group_addr_dict = defaultdict(list)
    for idx, row in group_info.iterrows():
        for i in range(5, n_students + 1):
            try:
                sid = str(int(row["SID{}".format(i)]))
                group_addr_dict[row["Group ID"]].append(gen_link_mail(sid))
            except:
                print("Pass: {}".format(row["SID{}".format(i)]))

    records = []
    for gid in group_addr_dict:
        print("Sending to {}".format(gid))
        receiver_list = [group_addr_dict[gid][-1]]
        receiver_list.append("csci3100@cse.cuhk.edu.hk")
        msg = text.format(
            gid,  # group id
            gid_projname[gid],
            gid_mark[gid],
        )

        records.append(
            {
                "GroupID": gid,
                "ProjectName": gid_projname[gid],
                "Msg": msg,
            }
        )

        # receiver_list = ["jyliu@cse.cuhk.edu.hk"]

        # # uncomment it to send emails
        send_mail_cse_smtp(
            "csci3100",  # cse username
            subject,  # subject
            msg,  # content
            None,  # no attachment
            receiver_list,  # receiver list
        )

        print("Sent to \n {}".format(receiver_list))
        print("\n" + subject)
        print(msg)
        print("-" * 20)

    pd.DataFrame(records).to_csv("{}_records.csv".format(phase), index=False)
    print("Done for {} teams.".format(len(records)))
